<?php
/* -------------------------------------------------------------------------------------
* 	ID:						$Id: ot_coupon.php 328 2013-09-28 10:34:48Z phone.mueller@googlemail.com $
* 	Letzter Stand:			$Revision: 328 $
* 	zuletzt geaendert von:	$Author: peter $
* 	Datum:					$Date: 2013-09-28 10:34:48 +0000 (Sat, 28 Sep 2013) $
*
* 	SEO:mercari by Siekiera Media
* 	http://www.seo-mercari.de
*
* 	Copyright (c) since 2011 SEO:mercari
* --------------------------------------------------------------------------------------
* 	based on:
* 	(c) 2000-2001 The Exchange Project  (earlier name of osCommerce)
* 	(c) 2002-2003 osCommerce - www.oscommerce.com
* 	(c) 2003     neommerce - www.neommerce.org
* 	(c) 2005     xt:Commerce - www.xt-commerce.com
*
* 	Released under the GNU General Public License
* ----------------------------------------------------------------------------------- */

class ot_coupon {
	var $title, $output, $db;

	function __construct() {
		global $price, $db;

		$this->code = 'ot_coupon';
		$this->header = MODULE_ORDER_TOTAL_COUPON_HEADER;
		$this->title = MODULE_ORDER_TOTAL_COUPON_TITLE;
		$this->description = MODULE_ORDER_TOTAL_COUPON_DESCRIPTION;
		$this->user_prompt = '';
		$this->enabled = MODULE_ORDER_TOTAL_COUPON_STATUS;
		$this->sort_order = MODULE_ORDER_TOTAL_COUPON_SORT_ORDER;
		$this->include_shipping = MODULE_ORDER_TOTAL_COUPON_INC_SHIPPING;
		$this->calculate_tax = MODULE_ORDER_TOTAL_COUPON_CALC_TAX;
		$this->credit_class = true;
		$this->output = array();
		$this->db = $db;

		if ($_SESSION['customers_status']['customers_status_show_price'] == 0)
			$this->enabled = 'false';
	}

	function process() {
		global $order, $price;

		if (isset ($_SESSION['cc_id']) && $this->enabled == 'true') {
			$order_total = $this->get_order_total();

			$this->deduction = $this->calculate_credit($order_total);

		   	if ($this->calculate_tax == 'true') {
				$this->tax_deduction = $this->calculate_tax_deduction($this->deduction, $order_total);
				$order->info['subtotal'] = round($order->info['subtotal'] - $this->deduction, 2);
			}

			if ($this->deduction > 0) {
				$order->info['deduction'] = $this->deduction;
				$order->info['total'] = $order->info['total'] - round($this->deduction, 2);
				if ($order->info['total'] < 0.0049) {
					$order->info['total'] = 0.00; 
					$order->info['tax'] = 0.00; 
				}
				$this->output[] = array ('title' => $this->title.' - <em>'.$this->coupon_code.'</em>:', 
										'text' => '<span style="color:#b2f0000"> -'.trim($price->format($this->deduction, true)).'</span>', 
										'value' => $price->format($this->deduction, false)); 
			}
		}
	}

	function get_order_total() {																
		global $order, $price;
		
		$order_total = 0.00;
		if (isset($order->info['tax_groups']) && is_array($order->info['tax_groups'])) {
  		reset($order->info['tax_groups']);
  		while (list ($key, $value) = each($order->info['tax_groups'])) {
  			$key_no_pre = str_replace(TAX_NO_TAX, "", $key);
  			$key_no_pre = str_replace(TAX_ADD_TAX, "", $key_no_pre);
  			$this->sum_tax["$key_no_pre"] = 0.00;
  		}
  	}

		$coupon_result = $this->db->db_query("SELECT 
													restrict_to_categories, 
													restrict_to_products 
												FROM 
													".TABLE_COUPONS."
												WHERE 
													coupon_id = '".(int)$_SESSION['cc_id']."' LIMIT 1");

		$products = $_SESSION['cart']->get_products();			
		for ($i = 0; $i < sizeof($products); $i ++) {

			$t_prid = get_prid($products[$i]['id']);
			if ($coupon_result->fields['restrict_to_categories'] == '' && $coupon_result->fields['restrict_to_products'] == '') {
				$products_price = $this->get_products_price($t_prid, $products[$i]['id']);
				$order_total += $_SESSION['cart']->contents[$products[$i]['id']]['qty'] * $products_price[0];
				$this->sum_tax["$products_price[1]"] += $_SESSION['cart']->contents[$products[$i]['id']]['qty'] * $products_price[0];

			} else if ($coupon_result->fields['restrict_to_categories'] != '') {
				$product_found = false;
				$cat_ids = explode(",", $coupon_result->fields['restrict_to_categories']);
				for ($ii = 0; $ii < count($cat_ids); $ii ++) {
					$subcat_ids = array ();
					require_once (DIR_FS_INC.'inc.get_subcategories.php');
					get_subcategories($subcat_ids, $cat_ids[$ii]);	
					if (sizeof($subcat_ids) > 0) {
						for ($iii = 0; $iii < sizeof($subcat_ids); $iii ++) {
							$cat_query = $this->db->db_query("SELECT 
																	products_id 
																FROM 
																	".TABLE_PRODUCTS_TO_CATEGORIES." 
																WHERE 
																	products_id = '".$t_prid."' 
																AND 
																	(categories_id = '".$cat_ids[$ii]."' OR categories_id = '".$subcat_ids[$iii]."')");
							if (db_num_rows($cat_query) != 0  && $product_found == false) {
								$products_price = $this->get_products_price($t_prid, $products[$i]['id']);
								$order_total += $_SESSION['cart']->contents[$products[$i]['id']]['qty'] * $products_price[0];
								$this->sum_tax["$products_price[1]"] += $_SESSION['cart']->contents[$products[$i]['id']]['qty'] * $products_price[0];
								$product_found = true;
							}
						}

					} else {				
						$cat = $this->db->db_query("SELECT 
														products_id 
													FROM 
														".TABLE_PRODUCTS_TO_CATEGORIES." 
													WHERE 
														products_id = '".$t_prid."' 
													AND 
														categories_id = '".$cat_ids[$ii]."'");
						if ($cat->_numOfRows  && $product_found == false) {
							$products_price = $this->get_products_price($t_prid, $products[$i]['id']);
							$order_total += $_SESSION['cart']->contents[$products[$i]['id']]['qty'] * $products_price[0];
							$this->sum_tax["$products_price[1]"] += $_SESSION['cart']->contents[$products[$i]['id']]['qty'] * $products_price[0];
							$product_found = true;
						}
					}
				}
				
			} else if ($coupon_result->fields['restrict_to_products'] != '') {
				$pr_ids = explode(",", $coupon_result->fields['restrict_to_products']);

				for ($ii = 0; $ii < count($pr_ids); $ii ++) {
					if ($t_prid == $pr_ids[$ii]){	
						$products_price = $this->get_products_price($t_prid, $products[$i]['id']);
						$order_total += $_SESSION['cart']->contents[$products[$i]['id']]['qty'] * $products_price[0];
						$this->sum_tax["$products_price[1]"] += $_SESSION['cart']->contents[$products[$i]['id']]['qty'] * $products_price[0];
					}
				}
			}		
		}
		
		if ($this->include_shipping == 'true') {
			$order_total = $order_total + $order->info['shipping_cost'];

	        $shipping_module = substr($_SESSION['shipping']['id'], 0, strpos($_SESSION['shipping']['id'], '_'));
			$shipping_tax_desc = get_tax_description($GLOBALS[$shipping_module]->tax_class, $order->delivery['country']['id'], $order->delivery['zone_id']);
			$this->sum_tax["$shipping_tax_desc"] += $order->info['shipping_cost'];
			
			if ($this->calculate_tax == 'false' && $_SESSION['customers_status']['customers_status_show_price_tax'] == 0 && $_SESSION['customers_status']['customers_status_add_tax_ot'] == 1) {
				$shipping_tax_rate = get_tax_rate($GLOBALS[$shipping_module]->tax_class, $order->delivery['country']['id'], $order->delivery['zone_id']);
				$order_total = $order_total + ($order->info['shipping_cost'] * ($shipping_tax_rate / 100 +1) - $order->info['shipping_cost']);
			}
		}
	
		return $order_total;
	}

	function calculate_credit($amount) {
		global $order;
			
		$coupon_result = $this->db->db_query("SELECT 
													coupon_type,
													coupon_amount, 
													coupon_code 
												FROM 
													".TABLE_COUPONS." 
												WHERE 
													coupon_id = '".(int)$_SESSION['cc_id']."' 
												LIMIT 1");

		$this->coupon_code = $coupon_result->fields['coupon_code'];
		$this->coupon_type = $coupon_result->fields['coupon_type'];

		if ($this->coupon_type == 'P')
			$od_amount = $amount * $coupon_result->fields['coupon_amount'] / 100;
		else if ($this->coupon_type == 'F')
			$od_amount = $coupon_result->fields['coupon_amount'];
		else if ($this->coupon_type == 'S') {
			$od_amount = $order->info['shipping_cost'];
			if ($this->include_shipping == 'false' && $_SESSION['customers_status']['customers_status_show_price_tax'] == 1) {
				$shipping_module = substr($_SESSION['shipping']['id'], 0, strpos($_SESSION['shipping']['id'], '_'));
				$shipping_tax_rate = get_tax_rate($GLOBALS[$shipping_module]->tax_class, $order->delivery['country']['id'], $order->delivery['zone_id']);
				$od_amount = $od_amount * ($shipping_tax_rate / 100 +1);
			}
			if ($this->calculate_tax == 'false'&& $_SESSION['customers_status']['customers_status_show_price_tax'] == 0 && $_SESSION['customers_status']['customers_status_add_tax_ot'] == 1) {
				$shipping_module = substr($_SESSION['shipping']['id'], 0, strpos($_SESSION['shipping']['id'], '_'));
				$shipping_tax_rate = get_tax_rate($GLOBALS[$shipping_module]->tax_class, $order->delivery['country']['id'], $order->delivery['zone_id']);
				$od_amount = $od_amount * ($shipping_tax_rate / 100 +1);
			}
		}

		if ($od_amount > $amount)
			$od_amount = $amount;
	
		return $od_amount;
	}

	function calculate_tax_deduction($od_amount, $order_total) {
		global $order;
		$tax_deduction = 0.00;
		
		if ($this->coupon_type == 'S') {
		    $shipping_module = substr($_SESSION['shipping']['id'], 0, strpos($_SESSION['shipping']['id'], '_'));
			$shipping_tax_rate = get_tax_rate($GLOBALS[$shipping_module]->tax_class, $order->delivery['country']['id'], $order->delivery['zone_id']);
			$shipping_tax_desc = get_tax_description($GLOBALS[$shipping_module]->tax_class, $order->delivery['country']['id'], $order->delivery['zone_id']);
			if ($_SESSION['customers_status']['customers_status_show_price_tax'] == 0 && $_SESSION['customers_status']['customers_status_add_tax_ot'] == 1) {
				$tax_deduction = ($od_amount * ($shipping_tax_rate / 100 + 1)) - $od_amount;
				$shipping_tax_desc = TAX_NO_TAX.$shipping_tax_desc;
			} else {
				$tax_deduction = $od_amount - ($od_amount / (100 + $shipping_tax_rate) * 100);
				$shipping_tax_desc = TAX_ADD_TAX.$shipping_tax_desc;
			}
			$order->info['tax_groups']["$shipping_tax_desc"] = $order->info['tax_groups']["$shipping_tax_desc"] - $tax_deduction;
			$order->info['tax'] = $order->info['tax'] - $tax_deduction;
			
		} else {
  		if (isset($order->info['tax_groups']) && is_array($order->info['tax_groups'])) {
  			reset($order->info['tax_groups']);
  			while (list ($key, $value) = each($order->info['tax_groups'])) {
  				if ($order->info['total'] - $od_amount <= 0.0049)
  					$order->info['tax_groups'][$key] = 0.00;
  	
  				else {
  					$key_no_pre = str_replace(TAX_NO_TAX, "", $key);
  					$key_no_pre = str_replace(TAX_ADD_TAX, "", $key_no_pre);
  					$tax_group_order_total = $this->sum_tax["$key_no_pre"] / $order_total;
  					$group_od_amount = $od_amount * $tax_group_order_total;
  					$tax_rate = get_tax_rate_from_desc($key_no_pre);
  					if ($_SESSION['customers_status']['customers_status_show_price_tax'] == 0 && $_SESSION['customers_status']['customers_status_add_tax_ot'] == 1)
  						$group_tax_deduction = ($group_od_amount * ($tax_rate / 100 + 1)) - $group_od_amount;
  					else
  						$group_tax_deduction = $group_od_amount - ($group_od_amount / (100 + $tax_rate) * 100);
  
  					$order->info['tax_groups'][$key] = $order->info['tax_groups'][$key] - $group_tax_deduction;
  					$order->info['tax'] = $order->info['tax'] - $group_tax_deduction;
  					$tax_deduction += $group_tax_deduction;
  				}
  			}
  		}
		}
		return $tax_deduction;
	}

	function get_products_price($t_prid, $products_id) {
		global $price, $order;
		$products_price = array();
		$product = $this->db->db_query("SELECT 
													products_tax_class_id 
												FROM 
													".TABLE_PRODUCTS." 
												WHERE 
													products_id='".$t_prid."' limit 1");
													
		if (isset ($_SESSION['cart']->contents[$products_id]['attributes'])) {
			while (list($option, $value) = each($_SESSION['cart']->contents[$products_id]['attributes'])) {
				$values = $price->GetOptionPrice($products_id, $option, $value);
				$attributes_price = $values['price'];
			}
		}

		$products_price[0] = $price->GetPrice($products_id, $format = false, 1, $product->fields['products_tax_class_id'], '', 1) + $attributes_price;
		if ($this->calculate_tax == 'false' && $_SESSION['customers_status']['customers_status_show_price_tax'] == 0 && $_SESSION['customers_status']['customers_status_add_tax_ot'] == 1) {
			$products_tax_rate = get_tax_rate($product->fields['products_tax_class_id'], $order->delivery['country']['id'], $order->delivery['zone_id']);
			$products_price[0] = $products_price[0] * ($products_tax_rate / 100 +1);
		}
		$products_price[1] = get_tax_description($product->fields['products_tax_class_id'], $order->delivery['country']['id'], $order->delivery['zone_id']);

		return $products_price;
	}

	function pre_confirmation_check($order_total) {
		if (isset($_SESSION['cc_id']) && $this->enabled == 'true') {
			$od_amount = $this->calculate_credit($order_total);
			return $od_amount;
		}
	}

	function use_credit_amount() {
		$use_credit_string = '';
		return $use_credit_string;
	}

	function credit_selection() {
		$selection_string = '';
		$selection_string .= '<tr>'."\n";
		$selection_string .= ' <td  nowrap class="main">'."\n";
		$selection_string .=  TEXT_ENTER_COUPON_CODE.'</td>';
		$selection_string .= ' <td  align="right">'. draw_input_field('gv_redeem_code').'</td>';
		$selection_string .= '</tr>'."\n";

		$selection_string = '';
		return $selection_string;
	}

	function apply_credit() {
		global $insert_id, $REMOTE_ADDR;
		
		if (!$REMOTE_ADDR) 
			$REMOTE_ADDR = $_SERVER['REMOTE_ADDR'];

		if ($this->deduction != 0) {
			$this->db->db_query("INSERT INTO 
									".TABLE_COUPON_REDEEM_TRACK." 
									(coupon_id, 
									redeem_date, 
									redeem_ip, 
									customer_id, 
									order_id) 
								VALUES 
									('".(int)$_SESSION['cc_id']."', 
									NOW(), 
									'".$REMOTE_ADDR."', 
									'".(int)$_SESSION['customer_id']."', 
									'".$insert_id."')");
		}
		unset($_SESSION['cc_id']);
	}

	function update_credit_account($i) {
		return false;
	}

	function collect_posts() {
		global $price;
		
		if ($_SESSION['cc_id'] != '') {
			$coupon_result = $this->db->db_query("SELECT 
														coupon_type, 
														coupon_start_date, 
														coupon_expire_date, 
														coupon_minimum_order, 
														coupon_id, 
														uses_per_user, 
														uses_per_coupon 
													FROM 
														".TABLE_COUPONS." 
													WHERE 
														coupon_id = '".(int)$_SESSION['cc_id']."' 
													AND 
														coupon_active = 'Y' limit 1");

			if ($coupon_result->fields['coupon_type'] != 'G') {
				if ($coupon_result->fields['coupon_start_date'] > date('Y-m-d H:i:s'))
					redirect(href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message='.urlencode(ERROR_INVALID_STARTDATE_COUPON), 'SSL'));
				if ($coupon_result->fields['coupon_expire_date'] < date('Y-m-d H:i:s'))
					redirect(href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message='.urlencode(ERROR_INVALID_FINISDATE_COUPON), 'SSL'));
				if ($coupon_result->fields['coupon_minimum_order'] > $_SESSION['cart']->show_total())
       		    	redirect(href_link(FILENAME_CHECKOUT_PAYMENT, 'info_message='.urlencode(ERROR_MINIMUM_ORDER_COUPON_1.' '.$price->format($coupon_result->fields['coupon_minimum_order'], true).' '.ERROR_MINIMUM_ORDER_COUPON_2), 'SSL'));

				$coupon_count = $this->db->db_query("SELECT coupon_id FROM ".TABLE_COUPON_REDEEM_TRACK." WHERE coupon_id = '".$coupon_result->fields['coupon_id']."'");
				
				if ($coupon_count->_numOfRows >= $coupon_result->fields['uses_per_coupon'] && $coupon_result->fields['uses_per_coupon'] > 0)
					redirect(href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message='.urlencode(ERROR_INVALID_USES_COUPON.$coupon_result->fields['uses_per_coupon'].TIMES), 'SSL'));

				$coupon_count_customer = $this->db->db_query("SELECT coupon_id FROM ".TABLE_COUPON_REDEEM_TRACK." WHERE coupon_id = '".$coupon_result->fields['coupon_id']."' AND customer_id = '".(int)$_SESSION['customer_id']."'");
				if ($coupon_count_customer->_numOfRows >= $coupon_result->fields['uses_per_user'] && $coupon_result->fields['uses_per_user'] > 0) {
					redirect(href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message='.urlencode(ERROR_INVALID_USES_USER_COUPON.$coupon_result->fields['uses_per_user'].TIMES), 'SSL'));
				}
			}
		}
	}

	function check() {
		if (!isset ($this->_check)) {
			$check = $this->db->db_query("SELECT configuration_value FROM ".TABLE_CONFIGURATION." WHERE configuration_key = 'MODULE_ORDER_TOTAL_COUPON_STATUS'");
			$this->_check = $check->_numOfRows;
		}
		return $this->_check;
	}

	function keys() {
		return array('MODULE_ORDER_TOTAL_COUPON_STATUS',
					'MODULE_ORDER_TOTAL_COUPON_SORT_ORDER',
					'MODULE_ORDER_TOTAL_COUPON_INC_SHIPPING',
					'MODULE_ORDER_TOTAL_COUPON_CALC_TAX');
	}

	function install() {
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('', 'MODULE_ORDER_TOTAL_COUPON_STATUS', 'true', '6', '1', 'cfg_select_option(array(\'true\', \'false\'), ', NOW())");
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('', 'MODULE_ORDER_TOTAL_COUPON_SORT_ORDER', '38', '6', '2', NOW())");
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, set_function ,date_added) values ('', 'MODULE_ORDER_TOTAL_COUPON_INC_SHIPPING', 'true', '6', '3', 'cfg_select_option(array(\'true\', \'false\'), ', NOW())");
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, set_function ,date_added) values ('', 'MODULE_ORDER_TOTAL_COUPON_CALC_TAX', 'true', '6', '4', 'cfg_select_option(array(\'true\', \'false\'), ', NOW())");
	}

	function remove() {
		$keys = '';
		$keys_array = $this->keys();
		for ($i = 0; $i < sizeof($keys_array); $i ++) {
			$keys .= "'".$keys_array[$i]."',";
		}
		$keys = substr($keys, 0, -1);

		$this->db->db_query("DELETE FROM ".TABLE_CONFIGURATION." WHERE configuration_key in (".$keys.")");
	}
}
?>